package com.styytech.dadabao.ui.my.accountset;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.loopj.android.http.RequestParams;
import com.styytech.dadabao.DadaApplication;
import com.styytech.dadabao.R;
import com.styytech.dadabao.adapter.BankCardAdapter;
import com.styytech.dadabao.api.requestresult.BankcardListResult;
import com.styytech.dadabao.api.requestresult.RegistResult;
import com.styytech.dadabao.api.response.AbstractResponseResult;
import com.styytech.dadabao.api.templates.HttpRequest;
import com.styytech.dadabao.base.BaseActivity;
import com.styytech.dadabao.bean.BankCard;
import com.styytech.dadabao.bean.ListData;
import com.styytech.dadabao.constant.ConstantsCommon;
import com.styytech.dadabao.constant.ConstantsServerUrl;
import com.styytech.dadabao.exception.ArgumentsException;
import com.styytech.dadabao.exception.RequestException;
import com.styytech.dadabao.utils.CommonUtils;
import com.styytech.dadabao.utils.SpUser;
import com.styytech.dadabao.widge.dialog.CustomAlertDialog;
import com.styytech.dadabao.widge.dialog.CustomLoadingDialog;

import java.util.LinkedList;

/**
 * 绑定银行卡管理
 */
@ContentView(R.layout.activity_bankcard_manage)
public class BankCardManageActivity extends BaseActivity {
    int first = 0;
    /*银行卡列表*/
    @ViewInject(R.id.lv_bankcard)
    ListView lv_bankcard;

    /*上下文*/
    private Context mContext;
    /*loading框*/
    CustomLoadingDialog mdlg;
    /*绑定银行卡适配器*/
    private BankCardAdapter mAdapter;
    /*银行卡数据列表*/
    private LinkedList<Object> mList;
    private int mListIndex = 0;
    private View view;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        initView();
        initData();
    }

    /**
     * 初始化视图
     */
    private void initView() {
        DadaApplication.addActivity(this);
        setTopBar("银行卡管理", View.VISIBLE);

        /*获取添加银行卡布局*/
        view = getLayoutInflater().inflate(R.layout.layout_add_bankcard, null);
        LinearLayout llyt_add_bankcard = (LinearLayout) view.findViewById(R.id.llyt_add_bankcard);
        llyt_add_bankcard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startNextActivity(AddBankCardActivity.class);
            }
        });
        lv_bankcard.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                mListIndex = i;
                displayDialog();
                return false;
            }
        });
    }

    /**
     * 显示对话框
     */
    private void displayDialog() {
        final CustomAlertDialog mdlg = new CustomAlertDialog(context, "解除绑定",
                "您确定要解除银行卡绑定吗？");
        mdlg.et_password.setVisibility(View.INVISIBLE);
        mdlg.tv_title.setVisibility(View.INVISIBLE);
        mdlg.et_password.setHeight(CommonUtils.dip2px(mContext,0));
        mdlg.tv_title.setHeight(CommonUtils.dip2px(mContext,20));
        mdlg.btn_ok.setText("确定");
        mdlg.dlg.setCancelable(false);
        mdlg.btn_cancel.setText("取消");
        mdlg.btn_ok.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                deleteBandCard();
                CommonUtils.closeDialog(mdlg);
            }

        });
        mdlg.btn_cancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                CommonUtils.closeDialog(mdlg);
            }
        });
        mdlg.show();
    }

    /**
     * 初始界面设置
     */
    private void initData() {
        mList = new LinkedList<Object>();
        /*获取已绑定银行卡的列表*/
        getBankCardList();
    }

    @OnClick({R.id.llyt_add_bankcard})
    public void click(View view) {
        switch (view.getId()) {
            case R.id.llyt_add_bankcard:// 添加银行卡
                startNextActivity(AddBankCardActivity.class);
                break;
        }
    }

    private void getBankCardList() {

        mdlg = CommonUtils.getCustomLoadingDialog(context, mdlg, "", true);
        mdlg.setMessage("loading...");
        mdlg.show();
        /*绑定银行卡请求参数*/
        RequestParams params = new RequestParams();
        /*提交实名认证请求*/
        submitRequest(params);
    }


    /**
     * 提交审核请求
     *
     * @param params 请求参数
     */
    private void submitRequest(RequestParams params) {
        String url = ConstantsServerUrl.getUserCardListUrl();// 获得用户账户绑定银行卡列表接口
        //获取验证码
        BankcardListResult bankcardlistResult = new BankcardListResult(responseResult, ConstantsCommon.DATA_SRC_BANKCARD);
        try {
            new HttpRequest(this).doPost(bankcardlistResult, url, params);
        } catch (ArgumentsException e) {
            Log.i("INFO", "1e:" + e);
            e.printStackTrace();
        } catch (RequestException e) {
            Log.i("INFO", "2e:" + e);
            e.printStackTrace();
        }
    }

    /**
     * 解除银行卡绑定请求
     */
    private void deleteBandCard(){
        mdlg = CommonUtils.getCustomLoadingDialog(context, mdlg, "解除绑定", true);
        mdlg.setMessage("loading...");
        mdlg.show();
        /*绑定银行卡请求参数*/
        RequestParams params = new RequestParams();
        BankCard bandCard = (BankCard)mList.get(mListIndex);
        params.put("userCardId",bandCard.getUserCardId());

        String url = ConstantsServerUrl.getDeleteUserCardUrl();// 获得用户账户绑定银行卡列表接口
        RegistResult  deleteBindCardResult = new RegistResult(responseResult1);
        try {
            new HttpRequest(this).doPost(deleteBindCardResult, url, params);
        } catch (ArgumentsException e) {
            Log.i("INFO", "1e:" + e);
            e.printStackTrace();
        } catch (RequestException e) {
            Log.i("INFO", "2e:" + e);
            e.printStackTrace();
        }
    }

    /**
     * 提交请求结果处理
     */
    AbstractResponseResult responseResult = new AbstractResponseResult() {

        @Override
        public void executeSuccess(Object object) {

            /*获取绑定数据列表*/
            mList = ((ListData) object).getDataList();
            if(mList.size() <= 0){// 如果银行卡都解除了，则设置未绑定过
                SpUser.setBankCardVStatus(mContext, 0);
            }
            mAdapter = new BankCardAdapter(mContext, mList);
            if (first == 0) {
                lv_bankcard.addFooterView(view);
                first++;
            }
            lv_bankcard.setAdapter(mAdapter);
            CommonUtils.closeDialog(mdlg);
        }

        @Override
        public void executeError(String message, int errorCode) {
            setView(View.VISIBLE, View.GONE, View.VISIBLE, View.VISIBLE, "" + message);
            CommonUtils.showToastMsg(context, "" + message);
            CommonUtils.closeDialog(mdlg);
        }

        @Override
        public void HttpError(String message, int errorCode) {
            setView(View.VISIBLE, View.GONE, View.VISIBLE, View.VISIBLE, "" + message);
            CommonUtils.showToastMsg(context, "" + message);
            CommonUtils.closeDialog(mdlg);
        }
    };

    /**
     * 提交请求结果处理
     */
    AbstractResponseResult responseResult1 = new AbstractResponseResult() {

        @Override
        public void executeSuccess(Object object) {
            initData();
            CommonUtils.showToastMsg(context, "" + "解除绑定成功");
            CommonUtils.closeDialog(mdlg);
        }

        @Override
        public void executeError(String message, int errorCode) {
            CommonUtils.showToastMsg(context, "" + message);
            CommonUtils.closeDialog(mdlg);
        }

        @Override
        public void HttpError(String message, int errorCode) {
            CommonUtils.showToastMsg(context, "" + message);
            CommonUtils.closeDialog(mdlg);
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        /*获取已绑定银行卡的列表*/
        getBankCardList();
    }

    /**
     * 启动界面
     *
     * @param cls 需要启动的界面类
     */
    private void startNextActivity(Class<?> cls) {
        Intent intent = new Intent(mContext, cls);
        startActivity(intent);
    }

    /**
     * 提示消息
     *
     * @param str 需要提示的消息
     */
    private void toast(String str) {
        Toast.makeText(mContext, str, Toast.LENGTH_SHORT).show();
    }

}

